package com.ctgu.tengyun.service.permission.impl;

import com.ctgu.tengyun.bean.response.RolePermission;
import com.ctgu.tengyun.dao.mybatis.PermissionRoleMapper;
import com.ctgu.tengyun.domain.PermissionResource;
import com.ctgu.tengyun.domain.PermissionRole;
import com.ctgu.tengyun.domain.PermissionRoleExample;
import com.ctgu.tengyun.service.permission.PermissionRoleService;
import com.ctgu.tengyun.util.CollectionsUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * Created by liaoweizhi on 2019/8/15.
 */
@Service
public class PermissionRoleServiceImpl implements PermissionRoleService {

    @Resource
    private PermissionRoleMapper mapper;

    @Override
    public List<PermissionRole> findByRoleId(Integer roleId) {
        PermissionRoleExample example = new PermissionRoleExample();
        PermissionRoleExample.Criteria criteria = example.createCriteria();

        criteria.andIsValidEqualTo(1);
        criteria.andRoleIdEqualTo(roleId);

        return mapper.selectByExample(example);
    }

    @Override
    public int upsert(RolePermission rolePermission) {
        Integer roleId = rolePermission.getRoleId();
        if(null == roleId){
            return 0;
        }

        List<PermissionResource> rolePermissionList = rolePermission.getRolePermissionList();

        PermissionRoleExample example = new PermissionRoleExample();
        PermissionRoleExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(roleId);

        PermissionRole permissionRole = new PermissionRole();
        permissionRole.setIsValid(0);
        mapper.updateByExampleSelective(permissionRole, example);

        if(!CollectionsUtil.isNullOrEmpty(rolePermissionList)){
            rolePermissionList.forEach(item -> {
                PermissionRole tempPermissionRole = new PermissionRole();
                tempPermissionRole.setRoleId(roleId);
                tempPermissionRole.setResourceId(item.getId());

                mapper.upsert(tempPermissionRole);
            });
        }

        return 1;
    }
}
